package com.smart.community.property.listener;

import com.smart.community.property.event.PermissionChangeEvent;
import com.smart.community.property.service.PermissionCacheRefreshService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 权限变更事件监听器
 * 用于监听权限变更事件并自动刷新相关缓存
 * 
 * @author Wu.Liang
 * @since 2025-06-29
 */
@Slf4j
@Component
public class PermissionChangeEventListener {

    @Autowired
    private PermissionCacheRefreshService cacheRefreshService;

    /**
     * 处理权限变更事件
     * 
     * @param event 权限变更事件
     */
    @Async
    @EventListener
    public void handlePermissionChangeEvent(PermissionChangeEvent event) {
        log.info("接收到权限变更事件: {}", event.getEventType());
        
        try {
            switch (event.getEventType()) {
                case USER_PERMISSION_CHANGE:
                    if (event.getUserId() != null) {
                        cacheRefreshService.refreshUserPermissionCache(event.getUserId());
                        log.info("用户权限缓存刷新完成，用户ID: {}", event.getUserId());
                    }
                    break;
                    
                case ROLE_PERMISSION_CHANGE:
                    if (event.getRoleId() != null) {
                        cacheRefreshService.refreshRolePermissionCache(event.getRoleId());
                        log.info("角色权限缓存刷新完成，角色ID: {}", event.getRoleId());
                    }
                    break;
                    
                case PROPERTY_COMPANY_CHANGE:
                    if (event.getPropertyCompanyId() != null) {
                        cacheRefreshService.refreshPropertyCompanyPermissionCache(event.getPropertyCompanyId());
                        log.info("物业公司权限缓存刷新完成，物业公司ID: {}", event.getPropertyCompanyId());
                    }
                    break;
                    
                case COMMUNITY_CHANGE:
                    if (event.getCommunityId() != null) {
                        cacheRefreshService.refreshCommunityPermissionCache(event.getCommunityId());
                        log.info("社区权限缓存刷新完成，社区ID: {}", event.getCommunityId());
                    }
                    break;
                    
                case ALL_PERMISSION_CHANGE:
                    cacheRefreshService.refreshAllPermissionCache();
                    log.info("所有权限缓存刷新完成");
                    break;
                    
                default:
                    log.warn("未知的权限变更事件类型: {}", event.getEventType());
                    break;
            }
        } catch (Exception e) {
            log.error("处理权限变更事件失败，事件类型: {}, 错误信息: {}", event.getEventType(), e.getMessage(), e);
        }
    }
} 